/**
 * @author yxw
 * date : 2013年10月29日 下午1:19:19 
 */
package com.tzinfo.tzt.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.MarginLayoutParams;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.tzinfo.tzt.R;
import com.tzinfo.tzt.activity.util.ConvertSwitch;
import com.tzinfo.tzt.activity.util.MyApplication;
import com.tzinfo.tzt.activity.view.ImagePagerAdapter;
import com.tzinfo.tzt.activity.view.MyProgressDialog;
import com.tzinfo.tzt.activity.view.VerticalScrollView;
import com.tzinfo.tzt.config.AppDataConfig;
import com.tzinfo.tzt.domain.MyResultList;
import com.tzinfo.tzt.domain.RenthouseDetail;
import com.tzinfo.tzt.domain.RenthouseList;
import com.tzinfo.tzt.util.HttpTools;
import com.tzinfo.tzt.util.JsonTools;
import com.tzinfo.tzt.util.ValidityTools;
import com.umeng.socialize.media.UMImage;

public class RentHouseDetailActivity extends BaseActivity implements
		OnClickListener {

	private List<Map<String, Object>> imgData;
	private Dialog dialog;
	private MyResultList rentHouseDetailResult;
	private ImageLoader imageLoader = ImageLoader.getInstance();
	private Intent thisIntent;
	private String sHouseId = "";
	private RenthouseDetail detail;
	private RenthouseList renthouseList;

	private DisplayImageOptions options;

	// 标志
	private boolean collectionChecked = false;

	// UI组件
	private Button backBtn, callBtn, falseBtn, collectionBtn, shareBtn;
	private VerticalScrollView mScrollView;
	private ImageView mapView, agentFaceImage, noPicView;
	private TextView[] textViews = new TextView[18];
	private ViewPager imagesPager;
	private ImagePagerAdapter imagePagerAdapter;
	private Button falsityBtn;
	private LinearLayout agentCompanyLayout;
	private RelativeLayout communityLayout;
	private RelativeLayout mapLayout;

	private Drawable drawableSelected;
	private Drawable drawableNormal;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_renthouse_detail);
		thisIntent = this.getIntent();
		sHouseId = thisIntent.getStringExtra("houseId");
		renthouseList = (RenthouseList) thisIntent
				.getSerializableExtra("renthouseList");
		setShareContent();
		init();
	}

	private void setShareContent() {
		String shareContent = String.format(
				this.getResources().getString(R.string.share_content),
				renthouseList.getName(), renthouseList.getLogo());
		// 设置分享内容
		mController.setShareContent(shareContent);
		// 设置分享图片, 参数2为图片的地址
		mController.setShareMedia(new UMImage(this, renthouseList.getLogo()));

		// 你在微信开发平台注册应用的App key,
		// 微信图文分享必须设置一个url
		String contentUrl = renthouseList.getLogo();
		// 添加微信朋友圈平台
		mController.getConfig().supportWXCirclePlatform(this,
				AppDataConfig.WXapp_id, contentUrl);
		mController.getConfig().supportWXPlatform(this, AppDataConfig.WXapp_id,
				contentUrl);
	}
	private void changeShareUrl(String Url) {
		String shareContent=String.format(
				this.getResources().getString(R.string.share_content),
				renthouseList.getName(), renthouseList.getLogo());
		// 设置分享内容
		mController
				.setShareContent(shareContent);
		// 设置分享图片, 参数2为图片的地址
		mController.setShareMedia(new UMImage(this,renthouseList.getLogo()));
		// 你在微信开发平台注册应用的App key,
		// 微信图文分享必须设置一个url
		// 添加微信朋友圈平台
		mController.getConfig()
				.supportWXCirclePlatform(this, AppDataConfig.WXapp_id, Url);
		mController.getConfig().supportWXPlatform(this, AppDataConfig.WXapp_id, Url);
	}
	private void init() {
		// 加载图片
		drawableSelected = getResources().getDrawable(
				R.drawable.top_50collection_selected);
		drawableNormal = getResources().getDrawable(
				R.drawable.top_50collection_normal);
		drawableSelected.setBounds(0, 0, drawableSelected.getMinimumWidth(),
				drawableSelected.getMinimumHeight());
		drawableNormal.setBounds(0, 0, drawableNormal.getMinimumWidth(),
				drawableNormal.getMinimumHeight());

		mapLayout = (RelativeLayout) this
				.findViewById(R.id.layout_house_location);
		mapLayout.setOnClickListener(this);

		// 显示地图控件
		mapView = (ImageView) this.findViewById(R.id.img_Address_Map);
		noPicView = (ImageView) this.findViewById(R.id.img_no_house_images);

		backBtn = (Button) this.findViewById(R.id.bt_back);
		backBtn.setOnClickListener(this);
		callBtn = (Button) this.findViewById(R.id.bt_call_agent);
		callBtn.setOnClickListener(this);
		falseBtn = (Button) this.findViewById(R.id.bt_Info_Falsity);
		falseBtn.setOnClickListener(this);
		shareBtn = (Button) this.findViewById(R.id.bt_share);
		shareBtn.setOnClickListener(this);
		collectionBtn = (Button) this.findViewById(R.id.bt_collection);
		collectionBtn.setOnClickListener(this);
		communityLayout = (RelativeLayout) this
				.findViewById(R.id.layout_of_community);
		communityLayout.setOnClickListener(this);
		// Infos
		textViews[0] = (TextView) this.findViewById(R.id.text_Infos_Name);
		textViews[2] = (TextView) this.findViewById(R.id.text_Infos_Price);
		textViews[3] = (TextView) this.findViewById(R.id.text_Infos_Style);
		textViews[4] = (TextView) this.findViewById(R.id.text_Infos_Size);
		textViews[5] = (TextView) this.findViewById(R.id.text_Infos_Direction);
		textViews[6] = (TextView) this.findViewById(R.id.text_Infos_Floor);
		textViews[7] = (TextView) this.findViewById(R.id.text_Infos_Decorate);
		textViews[8] = (TextView) this.findViewById(R.id.text_Infos_BuildType);
		textViews[9] = (TextView) this.findViewById(R.id.text_Infos_Device);
		textViews[10] = (TextView) this.findViewById(R.id.text_Infos_Describe);
		// 虚假反馈
		falsityBtn = (Button) this.findViewById(R.id.bt_Info_Falsity);
		falsityBtn.setOnClickListener(this);

		// Village
		textViews[11] = (TextView) this.findViewById(R.id.text_Village_Name);
		textViews[12] = (TextView) this.findViewById(R.id.un_Village_Id);
		textViews[13] = (TextView) this.findViewById(R.id.text_Village_Address);

		// Agent
		textViews[14] = (TextView) this.findViewById(R.id.un_Agent_ID);
		textViews[15] = (TextView) this.findViewById(R.id.text_Agent_Name);
		textViews[16] = (TextView) this.findViewById(R.id.text_Agent_Tel);
		textViews[17] = (TextView) this.findViewById(R.id.text_Agent_Company);
		agentFaceImage = (ImageView) this.findViewById(R.id.img_Agent_Face);
		agentCompanyLayout = (LinearLayout) this
				.findViewById(R.id.layout_Agent_Company);

		options = new DisplayImageOptions.Builder()
				.showImageOnLoading(R.drawable.ic_stub)
				.showImageForEmptyUri(R.drawable.ic_empty)
				.showImageOnFail(R.drawable.ic_error).cacheInMemory(true)
				.cacheOnDisc(true).bitmapConfig(Bitmap.Config.RGB_565).build();
		dialog = new MyProgressDialog(this).createDialog(getResources()
				.getString(R.string.loading));
		// 加载进度条
		dialog.show();
		imagesPager = (ViewPager) this.findViewById(R.id.pager_house_images);
		mScrollView = (VerticalScrollView) this.findViewById(R.id.scrollview);

		mScrollView.smoothScrollTo(0, 0);
		new Thread(getRentHouseDetailRun).start();
	}

	private void updateUI() {

		if (((RenthouseDetail) rentHouseDetailResult.getData().get(0))
				.getPics().size() == 0) {
			imagesPager.setVisibility(View.GONE);
			noPicView.setVisibility(View.VISIBLE);
		}

		imagePagerAdapter = new ImagePagerAdapter(this, imgData,
				R.layout.item_pager_image, new String[] { "img" },
				new int[] { R.id.image });
		imagesPager.setAdapter(imagePagerAdapter);
		imagesPager.setCurrentItem(0);

		// getInfos
		textViews[0].setText(detail.getInfos().getName());
		String price = detail.getInfos().getPrice();
		if ("0".equals(price)) {
			price = "售价待定";
		} else {
			price += "元/" + detail.getInfos().getPriceUnit();
		}
		textViews[2].setText(price);
		textViews[3].setText(detail.getInfos().getStyle());
		textViews[4].setText(detail.getInfos().getSize() + "平米");
		textViews[5].setText(detail.getInfos().getDirection());
		textViews[6].setText(detail.getInfos().getFloor());
		textViews[7].setText(detail.getInfos().getDecorate());
		textViews[8].setText(detail.getInfos().getBuildType());
		textViews[9].setText(detail.getInfos().getDevice());
		String describe = detail.getInfos().getDescribe();
		if (describe == null || "".equals(describe.trim())) {
			describe = "该房屋目前没有描述！";
		}
		textViews[10].setText(describe);
		String sFalsity = "虚假反馈(" + detail.getInfos().getFalsity() + ")";
		falsityBtn.setText(sFalsity);

		// getVillage
		textViews[11].setText(detail.getVillage().getName());
		textViews[12].setText(detail.getVillage().getID() + "");
		textViews[13].setText(detail.getVillage().getAddress());

		if (!"".equals(detail.getUrl()))
		changeShareUrl(detail.getUrl());
		// agentFaceImage
		if (detail.getAgent().getID() != 0) {
			textViews[17].setText(detail.getAgent().getCompany());
			LayoutParams params = new LayoutParams(
					MyApplication.widthPixels / 4,
					MyApplication.widthPixels / 4);
			params.setMargins(3, 0, 10, 0);
			agentFaceImage.setLayoutParams(params);
			imageLoader.displayImage(detail.getAgent().getFace(),
					agentFaceImage, options);
		} else {
			textViews[17].setVisibility(View.GONE);
			agentCompanyLayout.setVisibility(View.GONE);
		}
		textViews[14].setText(detail.getAgent().getID() + "");
		textViews[15].setText(detail.getAgent().getName());
		textViews[16].setText(detail.getAgent().getTel());
		// 显示百度地图
		String mapUrl = "http://api.map.baidu.com/staticimage?center="
				+ detail.getVillage().getLon() + ","
				+ detail.getVillage().getLat() + "&width="
				+ MyApplication.widthPixels + "&height="
				+ MyApplication.widthPixels * 0.75 + "&zoom=12";
		Log.d("mapUrl", mapUrl);
		imageLoader.displayImage(mapUrl, mapView, options);
		// 检测是否已收藏
		if ((collectionChecked = collectionService.getRentHouseById(sHouseId) != null ? true
				: false)) {
			collectionBtn.setCompoundDrawables(drawableSelected, null, null,
					null);
		}
		mScrollView.smoothScrollTo(0, 0);
	}

	private void getDataError(String ERRORMESSAGE) {
		new AlertDialog.Builder(this).setCancelable(false)
				.setMessage(ERRORMESSAGE)
				.setPositiveButton(getResources().getString

				(R.string.cancel), new DialogInterface.OnClickListener()

				{
					public void onClick

					(DialogInterface dialog, int which) {
						finish();
					}
				}).setNegativeButton(getResources().getString

				(R.string.try_again), new DialogInterface.OnClickListener()

				{
					public void onClick(

					DialogInterface dialogInterface, int

					whichButton) {
						dialog.show();
						new Thread(getRentHouseDetailRun).start();
					}
				}).show();
	}

	@SuppressLint("HandlerLeak")
	Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.arg1) {
			case 1:
				updateUI();
				dialog.dismiss();
				break;
			case -1:
				getDataError((String) msg.obj);
				break;
			case 5:
				break;
			case 7:
				break;
			case 0:
				break;
			}
		}
	};

	/**
	 * 线程 得到新房列表
	 */
	Runnable getRentHouseDetailRun = new Runnable() {

		@Override
		public void run() {
			Message msg = handler.obtainMessage();
			String jsonString;
			String url = AppDataConfig.zufangUrl
					+ AppDataConfig.RenthouseDetail + "?id=" + sHouseId;
			Log.e("url", url);
			jsonString = HttpTools.getJsonContent(url);
			Log.e("JsonString", jsonString);
			rentHouseDetailResult = JsonTools.getRenthouseDetail(jsonString);
			getData();
			if (rentHouseDetailResult.getSuccess()) {
				msg.arg1 = 1;
			} else {
				msg.arg1 = -1;
				msg.obj = rentHouseDetailResult.getErrorMessage();
			}
			handler.sendMessage(msg);
		}
	};

	// 得到data数据
	private void getData() {
		imgData = new ArrayList<Map<String, Object>>();
		Map<String, Object> map;
		if (rentHouseDetailResult.getSuccess()) {
			Log.e("size", rentHouseDetailResult.getData().size() + "");
			detail = (RenthouseDetail) rentHouseDetailResult.getData().get(0);
			List<String> pics = detail.getPics();
			if (pics == null || pics.size() == 0) {
				map = new HashMap<String, Object>();
				map.put("img", R.drawable.guide05);
				imgData.add(map);
			}
			for (int i = 0; i < pics.size(); i++) {
				map = new HashMap<String, Object>();
				map.put("img", pics.get(i));
				imgData.add(map);
			}

		}

	}

	public void setListViewHeightBasedOnChildren(ListView listView) {
		ListAdapter listAdapter = listView.getAdapter();
		if (listAdapter == null) {
			return;
		}
		int totalHeight = 0;
		for (int i = 0; i < listAdapter.getCount(); i++) {
			View listItem = listAdapter.getView(i, null, listView);
			listItem.measure(0, 0);
			totalHeight += listItem.getMeasuredHeight();
		}
		ViewGroup.LayoutParams params = listView.getLayoutParams();
		params.height = 1 + totalHeight
				+ (listView.getDividerHeight() * (listAdapter.getCount() - 1));
		((MarginLayoutParams) params).setMargins(10, 10, 10, 10);
		listView.setLayoutParams(params);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.bt_back:
			this.finish();
			break;
		case R.id.bt_share:
			// 打开平台选择面板，参数2为打开分享面板时是否强制登录,false为不强制登录
			mController.openShare(this, false);
			break;
		case R.id.bt_collection:
			// 收藏与取消
			if (collectionChecked) {
				// sharedPreferences.removeMapItemMessage(
				// AppDataConfig.CollectionKeys[3], renthouseList.getID()
				// + "");
				collectionService.deleteRentById(sHouseId);
				collectionBtn.setCompoundDrawables(drawableNormal, null, null,
						null);
				collectionChecked = false;
				Toast.makeText(this, "取消收藏！", Toast.LENGTH_SHORT).show();
			} else {
				// sharedPreferences.saveMapItemMessage(
				// AppDataConfig.CollectionKeys[3], renthouseList.getID()
				// + "", renthouseList);
				collectionService.saveRentHouse(renthouseList);
				collectionBtn.setCompoundDrawables(drawableSelected, null,
						null, null);
				// collectionBtn.setBackgroundResource(R.drawable.top_50collection_selected);
				Toast.makeText(this, "收藏成功！", Toast.LENGTH_SHORT).show();
				collectionChecked = true;
			}

			break;
		case R.id.bt_call_agent:
			String tel = detail.getAgent().getTel();
			if (tel == null || "".equals(tel)) {
				Toast.makeText(this, "抱歉，该经纪人没有提供电话！", Toast.LENGTH_SHORT).show();
			} else {
				tel=ValidityTools.checkFenjihao(tel);
				Intent phoneIntent = new Intent("android.intent.action.CALL",
						Uri.parse("tel:" + tel));
				startActivity(phoneIntent);
				callService.saveRentHouse(renthouseList);
			}
			break;
		case R.id.bt_Info_Falsity:
			Intent falsityIntent = new Intent(this,
					FalseInformationActivity.class);
			falsityIntent.putExtra("houseid", detail.getID());
			falsityIntent.putExtra("tabNum", 2);
			falsityIntent.putExtra("houseName", detail.getInfos().getName());
			startActivity(falsityIntent);
			break;
		case R.id.layout_of_community:
			Intent communityIntent = new Intent(this,
					RenthouseVillageAcitivity.class);
			communityIntent.putExtra("villageId", detail.getVillage().getID());
			startActivity(communityIntent);
			break;
		case R.id.layout_house_location:
			Intent mapIntent = new Intent(this, MapRoutePlanActivity.class);
			ConvertSwitch.Convert_GCJ02_To_BD09(detail.getVillage().getLat(), detail.getVillage().getLon());
			MapRoutePlanActivity.houseName=renthouseList.getName();
			mapIntent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
			startActivity(mapIntent);
			break;
		}

	}
}
